package com.liu.utils;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUpdate {

    //前端设置post  enctype:multipart/form-data  二进制流

    //文件上传
    public void fileUpload(CommonsMultipartFile file, HttpServletRequest request) throws IOException {


        String uploadFile  = file.getOriginalFilename();


        String path = request.getServletContext().getRealPath("/upload");

        File realoath = new File(path);


        InputStream inputStream = file.getInputStream();

        OutputStream outputStream = new FileOutputStream(new File(realoath,uploadFile));

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = inputStream.read(buffer))  != -1 ){
            outputStream.write(buffer,0,len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();


    }


    //文件上传
    public void fileUpload2(CommonsMultipartFile file, HttpServletRequest request) throws IOException {


        String path = request.getServletContext().getRealPath("/upload");
        File file1 = new File(path);


        file.transferTo(new File(file1,path + "/"+file.getOriginalFilename()));


    }

    //文件下载
    public void downloads(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = request.getServletContext().getRealPath("/upload");
        String name = "文件名.jpg";


        //设置相应头
        response.reset();//设置界面不缓存
        response.setCharacterEncoding("UTF-8");//设置编码
        response.setContentType("multipart/form-data");//设置二进制传输数据

        //设置相应头
        response.setHeader("Content-Disposition","attachment:fileName" + URLEncoder.encode(name,"UTF-8"));
        File file = new File(path,name);


        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();

        byte[] buff = new byte[1024];

        int index=0;
        while ((index=inputStream.read(buff))!=-1){
        outputStream.write(buff,0,index);
        outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        //结束




    }












}
